//搜索列表页
var router =require('express').Router();
var async=require('async');
var Book=require('../model/book');
var Comment=require('../model/comment');
var cats=require('../cats');
var reg=require('../lib/reg');
var page=require('../lib/page');
var sortMap={
    1:{
        number:1,field:'sales',key:-1
    },
    2:{
        number:2,field:'price',key:1
    },
    22:{
        number:22,field:'price',key:-1
    },
    4:{
        number:4,field:'putaway',key:-1
    }
};
var catsMap=(()=>{
    var catsMap={};
    cats.forEach((cat)=>{
        catsMap[cat.id]=cat;
    });
    return catsMap;
})();

var hl=(reg,books)=>{
    books.forEach((book)=>{
        book.name=book.name.replace(reg,'<em>$1</em>');
    });
    return books;
};
var syncIds=(bookIds,books)=>{
    var ret=[];
    for(var i=0;i<bookIds.length;i++){
        for(var j=0;j<books.length;j++){
            if(bookIds[i].toString()==books[j]._id.toString()){
                ret.push(books[j]);
                break;
            }
        }
    }
    return ret;
};

var sortFn=(function(){

    return {
        find: (opts,req,res,next)=>{
            async.parallel({
                count:(pCb)=>{
                    Book.count({name:opts.nameReg},(err,count)=>{
                        if(err)return pCb(err);
                        pCb(null,count);
                    });
                },
                books:(pCb)=>{
                    Book.page({name:opts.nameReg},{},{sort:{[opts.sort.field]:opts.sort.key},page:opts.page},(err,books)=>{
                        if(err)return pCb(err);
                        books=hl(opts.nameReg,books);
                        pCb(null,books);
                    });
                }
            },(err,ret)=>{
                if(err)return next(err);
                var curr=Number(opts.page)||1,count=ret.count,total=Math.ceil(count/(opts.limit || 20));
                res.render('search',
                    {
                        title:opts.keyword+' - 商品搜索',
                        user:req.session.user,
                        books:ret.books,
                        keyword:opts.keyword,
                        curr:{[opts.sort.field]:true},
                        numbers:opts.numbers,
                        priceSort:opts.priceSort,
                        page:Object.assign(page(curr,total),{
                            curr:curr,
                            count:count,
                            total:total,
                            sort:opts.sort.number,
                            uri:'/search?'+['keyword='+opts.keyword,'sort='+opts.sort.number].join('&')
                        })
                    }
                );
            });
        },

        comment: (opts,req,res,next)=>{
            async.parallel({
                count:(pCb)=>{
                    Book.count({name:opts.nameReg},(err,count)=>{
                        if(err)return pCb(err);
                        pCb(null,count);
                    });
                },
                books:(pCb)=>{
                    async.waterfall([
                        (cb)=>{
                            Book.find({name:opts.nameReg},{comment:true},(err,books)=>{
                                if(err)return cb(err);
                                var commentIds=books.map((book)=>{
                                    return book.comment;
                                });
                                cb(null,commentIds);
                            });
                        },
                        (commentIds,cb)=>{
                            Comment.page({_id:{$in:commentIds}},{book:true,commentCount:true},{sort:{commentCount:-1}},(err,comments)=>{
                                if(err)return cb(err);
                                var bookIds=comments.map((comment)=>{
                                    return comment.book;
                                });
                                cb(null,bookIds);
                            });
                        },
                        (bookIds,cb)=>{
                            Book.page({_id:{$in:bookIds}},{_id:true},{page:opts.page},(err,books)=>{
                                if(err)return cb(err);
                                books=syncIds(bookIds,books);
                                cb(null,books);
                            });
                        }
                    ],(err,books)=>{
                       if(err)return pCb(err);
                        books=hl(opts.nameReg,books);
                        pCb(null,books);
                    });
                }
            },(err,ret)=>{
                if(err)return next(err);
                var curr=Number(opts.page)||1,count=ret.count,total=Math.ceil(count/(opts.limit || 20));
                res.render('search',
                    {
                        title:opts.keyword+' - 商品搜索',
                        user:req.session.user,
                        books:ret.books,
                        keyword:opts.keyword,
                        curr:{commentCount:true},
                        numbers:opts.numbers,
                        priceSort:{},
                        page:Object.assign(page(curr,total),{
                            curr:curr,
                            count:count,
                            total:total,
                            sort:3,
                            uri:'/search?'+['keyword='+opts.keyword,'sort=3'].join('&')
                        })
                    }
                );
            });
        },

        comprehensive: (opts,req,res,next)=>{
            async.parallel({
                count:(pCb)=>{
                    Book.count({name:opts.nameReg},(err,count)=>{
                        if(err)return pCb(err);
                        pCb(null,count);
                    });
                },
                books:(pCb)=>{
                    async.waterfall([
                        (cb)=>{
                            Book.page({name:opts.nameReg},{sales:true,comment:true},{page:opts.page,sort:{sales:-1}},(err,books)=>{
                                if(err)return cb(err);
                                var commentIds=books.map((book)=>{
                                    return book.comment;
                                });
                                cb(null,commentIds);
                            });
                        },
                        (commentIds,cb)=>{
                            Comment.page({_id:{$in:commentIds}},{book:true,goodRate:true},{sort:{goodRate:-1}},(err,comments)=>{
                                if(err)return cb(err);
                                var bookIds=comments.map((comment)=>{
                                    return comment.book;
                                });
                                cb(null,bookIds);
                            });
                        },
                        (bookIds,cb)=>{
                            Book.page({_id:{$in:bookIds}},{_id:true},{},(err,books)=>{
                                if(err)return cb(err);
                                books=syncIds(bookIds,books);
                                cb(null,books);
                            });
                        }
                    ],(err,books)=>{
                        if(err)return pCb(err);
                        books=hl(opts.nameReg,books);
                        pCb(null,books);
                    });
                }
            },(err,ret)=>{
                if(err)return next(err);
                var curr=Number(opts.page)||1,count=ret.count,total=Math.ceil(count/(opts.limit || 20));
                res.render('search',
                    {
                        title:opts.keyword+' - 商品搜索',
                        user:req.session.user,
                        books:ret.books,
                        keyword:opts.keyword,
                        curr:{comprehensive:true},
                        numbers:opts.numbers,
                        priceSort:{},
                        page:Object.assign(page(curr,total),{
                            curr:curr,
                            count:count,
                            total:total,
                            sort:0,
                            uri:'/search?'+['keyword='+opts.keyword,'sort=0'].join('&')
                        })
                    }
                );
            });
        }
    }
})();


module.exports = router;
router.get('/',(req, res,next)=>{
    var keyword=req.query.keyword;
    var nameReg=new RegExp('('+keyword.replace(/(\W+)/g,'\\$1')+')','ig');//转义特殊字符
    var sort=req.query.sort;
    var page=Number(req.query.page)||1;
    var fn;
    var numbers={
        sales:1,
        price:2,
        putaway:4,
        comprehensive:0,
        commentCount:3
    };
    var priceSort={
        asc:2==sort,
        desc:22==sort
    };
    if(1==sort || 2==sort || 22==sort || 4==sort){
        fn='find';
        if(2==sort){
            numbers.price=22;
        }else{
            numbers.price=2;
        }
    }else if(3==sort){
        fn='comment';
    }else{//0和其它排序值为“综合排序”
        fn='comprehensive';
    }
    sort=sortMap[sort];
    var opts={keyword:keyword,nameReg:nameReg,sort:sort,numbers:numbers,priceSort:priceSort,page:page};
    sortFn[fn](opts,req,res,next);
});